﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Reporting.WinForms;
using Zvezda.FSO2.DB;
using Telerik.WinControls.UI;
using System.Xml;
using Telerik.WinControls;

namespace FSO.Reports
{
    /// <summary>
    /// Компонент для отображения параметров отчета "Оплаченные изделия"
    /// </summary>
    public partial class UserControlPaidMaterialsParams : UserControl, IReportParamList
    {
        private RadDropDownMenu contextMenu = new RadDropDownMenu();
        private List<int> selectedIndexes = new List<int>();

		private void AddCheckColumn()
		{
			CustomCheckBoxColumn checkColumn = new CustomCheckBoxColumn();
			checkColumn.Name = "Select";
			checkColumn.Width = 82;
			this.radListControlProducts.Columns.Insert(0, checkColumn);
		}

        public class MyGridBehavior : BaseGridBehavior
        {
            public override bool OnMouseWheel(MouseEventArgs e)
            {
                ((UserControlPaidMaterialsParams)GridControl.Parent).VScrollBar_Scroll(null, null);
                return base.OnMouseWheel(e);
            }
        }

        public UserControlPaidMaterialsParams()
        {
            InitializeComponent();
			this.AddCheckColumn();
            radListControlProducts.GridBehavior = new MyGridBehavior();
			radListControlProducts.CellFormatting+=new CellFormattingEventHandler(radListControlProducts_CellFormatting);
        }

		void radListControlProducts_CellFormatting(object sender, CellFormattingEventArgs e)
		{
			if (e.CellElement is GridFilterCellElement && e.CellElement.ColumnInfo.Name == "Select")
			{
				e.CellElement.Children.Clear();
			}
		}
        #region IReportParamList Members

        public Microsoft.Reporting.WinForms.ReportParameter[] Parameters
        {
            get 
            {
                List<ReportParameter> _listParams = new List<ReportParameter>(3);

                string sTypeOfActivityValue = null;
                string sTypeOfActivityName = null;
                if (!userControlTypeOfActivitySelector1.IsNull)
                {
                    sTypeOfActivityValue = userControlTypeOfActivitySelector1.SelectedValue;
                    sTypeOfActivityName = userControlTypeOfActivitySelector1.SelectedText;
                }
                _listParams.Add(new ReportParameter("p_nsi_type_of_activity_id", sTypeOfActivityValue, false));
                _listParams.Add(new ReportParameter("v_nsi_type_of_activity", sTypeOfActivityName, false));

                string sContractValue = null;
                string sContractNumber = null;
                if (!userControlContractSelector1.IsNull)
                {
                    sContractValue = userControlContractSelector1.SelectedRow.ID.ToString();
                    sContractNumber = userControlContractSelector1.SelectedRow.NUMBER;
                }
                _listParams.Add(new ReportParameter("p_contract_id", sContractValue, false));
                _listParams.Add(new ReportParameter("v_contract_number", sContractNumber, false));

                string sNsiOrganization = null;
                string sNsiOrganizationName = null;
                if (!userControlOrganizationSelector1.IsNull)
                {
                    sNsiOrganization = userControlOrganizationSelector1.SelectedRow.ID.ToString();
                    sNsiOrganizationName = userControlOrganizationSelector1.SelectedRow.SHORT_NAME;
                }
               
                _listParams.Add(new ReportParameter("p_nsi_organization_id", sNsiOrganization, false));
                _listParams.Add(new ReportParameter("v_organization", sNsiOrganizationName, false));

                string sXmlMaterials = null;
                string sProducts = null;
                if (radCheckBoxMaterialsIsNull.ToggleState == Telerik.WinControls.Enumerations.ToggleState.On)
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    XmlNode nodeMaterials = xmlDoc.CreateNode(XmlNodeType.Element, "products", "");
                    xmlDoc.AppendChild(nodeMaterials);
                    if (selectedIndexes.Count != 0)
                    //{
					//    foreach (GridViewRowInfo item in radListControlProducts.SelectedRows)
					//    {
					//        XmlNode nodeMaterial = xmlDoc.CreateNode(XmlNodeType.Element, "product", "");
					//        XmlAttribute att = xmlDoc.CreateAttribute("id");
					//        att.Value = item.Cells[1].Value.ToString();
					//        nodeMaterial.Attributes.Append(att);
					//        nodeMaterials.AppendChild(nodeMaterial);

					//        if (sProducts != null)
					//        {
					//            sProducts += ", ";
					//        }
					//        sProducts += item.Cells[1].Value.ToString();
					//    }
					//}
					//else
                    {
                        foreach (var i in selectedIndexes)
                        {
                            //GridViewRowInfo item = null;
                            //try
                            //{
                            //    item = radListControlProducts.Rows[i];
                            //}
                            //catch
                            //{
                            //    continue;
                            //}
                            //if (item == null) break;
                            XmlNode nodeMaterial = xmlDoc.CreateNode(XmlNodeType.Element, "product", "");
                            XmlAttribute att = xmlDoc.CreateAttribute("id");
                            att.Value = i.ToString();//item.Cells[1].Value.ToString();
                            nodeMaterial.Attributes.Append(att);
                            nodeMaterials.AppendChild(nodeMaterial);

                            if (sProducts != null)
                            {
                                sProducts += ", ";
                            }
                            sProducts += i.ToString();//item.Cells[1].Value.ToString();
                        }
                    }
					if (nodeMaterials.ChildNodes.Count > 0)
						sXmlMaterials = xmlDoc.InnerXml;
					else
						sXmlMaterials = null;
                }
                ReportParameter paramXmlProducts = new ReportParameter("p_xml_products", sXmlMaterials, false);
                _listParams.Add(paramXmlProducts);
                ReportParameter paramVProducts = new ReportParameter("v_products", sProducts, false);
                _listParams.Add(paramVProducts);

                // Дата с
                _listParams.Add(new ReportParameter("p_date_from", userControlDatePeriodSelector1.DateFrom.ToShortDateString(), false));

                // Дата по
                _listParams.Add(new ReportParameter("p_date_to", userControlDatePeriodSelector1.DateTo.ToShortDateString(), false));

                return _listParams.ToArray();
            }
        }

        #endregion

        /// <summary>
        /// Загружает данные из БД
        /// </summary>
        private void UserControlRecievedMeansParams_Load(object sender, EventArgs e)
        {
            tableAdapterManager1.NSI_PRODUCTTableAdapter.Fill(dataSetFSO1.NSI_PRODUCT);
			nsI_PRODUCTTableAdapter1.Fill(dataSetFSO1.NSI_PRODUCT);
        }

        private void radCheckBoxMaterialsIsNull_ToggleStateChanged(object sender, Telerik.WinControls.UI.StateChangedEventArgs args)
        {
            if (args.ToggleState == Telerik.WinControls.Enumerations.ToggleState.On)
            {
                radListControlProducts.Enabled = true;
            }
            else
            {
                radListControlProducts.Enabled = false;
            }
        }

        private void radListControlProducts_ContextMenuOpening(object sender, ContextMenuOpeningEventArgs e)
        {
            GridDataCellElement cell = e.ContextMenuProvider as GridDataCellElement;
            if (cell == null)
            {
                return;
            }
            e.ContextMenu = contextMenu;
        }

        void radListControlProducts_MouseClick(object sender, MouseEventArgs e)
        {
            var dataCell = this.radListControlProducts.ElementTree.GetElementAtPoint(e.Location) as GridDataCellElement;
            var checkMark = this.radListControlProducts.ElementTree.GetElementAtPoint(e.Location) as RadCheckmark;
			var header = this.radListControlProducts.ElementTree.GetElementAtPoint(e.Location).Parent as CheckBoxHeaderCell;
            if (dataCell != null || checkMark != null)
            {
                if (dataCell != null)
                {
					try
					{
						if (!selectedIndexes.Contains((int)dataCell.RowInfo.Cells[1].Value))
						{
							selectedIndexes.Add((int)dataCell.RowInfo.Cells[1].Value);
							dataCell.RowInfo.Cells["Select"].Value = true;
						}
						else
						{
							selectedIndexes.Remove((int)dataCell.RowInfo.Cells[1].Value);
							dataCell.RowInfo.Cells["Select"].Value = false;
						}
					}
                    catch (Exception)
                    {
                    }
                }
                else
                {
                    switch (checkMark.CheckState)
                    {
                        case Telerik.WinControls.Enumerations.ToggleState.Off:
                            checkMark.CheckState = Telerik.WinControls.Enumerations.ToggleState.On;
							if (radListControlProducts.CurrentRow.Cells[1].Value != null && 
								!selectedIndexes.Contains((int)radListControlProducts.CurrentRow.Cells[1].Value))
									selectedIndexes.Add((int)radListControlProducts.CurrentRow.Cells[1].Value);
                            break;
                        case Telerik.WinControls.Enumerations.ToggleState.On:
                            checkMark.CheckState = Telerik.WinControls.Enumerations.ToggleState.Off;
							if(radListControlProducts.CurrentRow.Cells[1].Value!= null)
								selectedIndexes.Remove((int)radListControlProducts.CurrentRow.Cells[1].Value);
                            break;
                    }
                }
			}
			else if (header != null)
			{
				var value = (header.GetChildrenByBaseType(typeof(RadCheckBoxElement))[0] as RadCheckBoxElement).ToggleState;
				if (value == Telerik.WinControls.Enumerations.ToggleState.Off)
				{
					//значит состояние изменяется на On
					selectedIndexes.AddRange(radListControlProducts.ChildRows.Select(x => (int)x.Cells[1].Value));
					selectedIndexes = selectedIndexes.Distinct().ToList();
				}
				else
				{
					foreach (var item in radListControlProducts.ChildRows.Select(x => (int)x.Cells[1].Value))
						selectedIndexes.Remove(item);
				}
			}
        }
        void VScrollBar_Scroll(object sender, System.Windows.Forms.ScrollEventArgs e)
        {
            foreach (var i in selectedIndexes)
            {
                try
                {
					GridViewRowInfo item = radListControlProducts.Rows.FirstOrDefault(x => (int)x.Cells[1].Value == i);
                    item.Cells["Select"].Value = true;
                }
                catch { }
            }
        }
    }
}
